﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web.UI;

public partial class BarangKeluarPerLab : System.Web.UI.Page
{
    private static string strConn = ConfigurationManager.ConnectionStrings["LabConnectionString"].ConnectionString;
    private const string PREFIX = "jumlah_";
    protected void Page_Load(object sender, EventArgs e)
    {
        btnKirim.Enabled = false;
        if (!IsPostBack)
        {
            populateTahunAnggaran();
            populateLab();
        }
    }

    protected void btnKirim_Click(object sender, EventArgs e)
    {
        List<string> keys = new List<string>();
        List<string> values = new List<string>();

        foreach (string key in Request.Form.Keys)
        {
            if (key.StartsWith(PREFIX))
            {
                double value = 0;
                if (double.TryParse(Request.Form[key], out value) && value > 0)
                {
                    keys.Add(key.Substring(PREFIX.Length));
                    values.Add(value.ToString());
                }
            }
        }
        //showMessage("keys", string.Join(", ", keys), "error");
        //showMessage("values", string.Join(", ", values), "error");

        if (keys.Count == 0)
        {
            showMessage("Terjadi Kesalahan", "Mohon isi data dengan benar", "error");
            return;
        }

        try
        {
            using (SqlConnection cn = new SqlConnection(strConn))
            {
                cn.Open();
                string query = "sp_barang_keluar_per_lab {0}, {1}, {2}, '{3}', '{4}'";
                using (SqlCommand cmd = new SqlCommand(string.Format(query, lstTahun.SelectedValue, lstLab.SelectedValue, Session["idUser"], string.Join(", ", keys), string.Join(", ", values))))
                {
                    cmd.Connection = cn;
                    int ra = cmd.ExecuteNonQuery();
                    if (ra > 0)
                    {
                        populateList1();
                        showMessage("Sukses", "Barang Keluar sudah disimpan", "success");
                    }
                    else
                    {
                        showMessage("Terjadi Kesalahan", "Tidak ada data yang berhasil ditulis.", "error");
                    }
                }
                cn.Close();
            }
        }
        catch (Exception ex)
        {
            showMessage("Terjadi Kesalahan", "Gagal mengupdate barang keluar : " + ex.Message, "error");
        }
        populateList1();
        populateList2();
    }

    private void populateLab()
    {
        string query = "sp_namalab_list";
        DataTable dt = new DataTable();
        using (SqlDataAdapter da = new SqlDataAdapter(query, strConn))
        {
            da.Fill(dt);
        }
        var dr = dt.NewRow();
        dt.Rows.InsertAt(dr, 0);

        lstLab.DataSource = dt;
        lstLab.DataTextField = "NAMA";
        lstLab.DataValueField = "ID";
        lstLab.DataBind();
    }

    private void showMessage(string caption, string message, string type)
    {
        message = message.Replace("'", "&apos;");
        message = message.Replace(Environment.NewLine, "<br />");
        string clientScript = "$(document).ready(function(){ new PNotify({ title: '" + caption + "', text: '" + message + "', type: '" + type + "',styling: 'bootstrap3' }); });";
        ScriptManager.RegisterStartupScript(Page, this.GetType(), "ShowMessage", clientScript, true);
    }

    private void populateTahunAnggaran()
    {
        string query = "sp_get_tahun_anggaran";
        DataTable dt = new DataTable();
        using (SqlDataAdapter da = new SqlDataAdapter(query, strConn))
        {
            da.Fill(dt);
        }
        DataTable tahun = new DataTable();
        tahun.Columns.Add("TAHUN");
        if (dt.Rows.Count > 0)
        {
            DataRow dr = tahun.NewRow();
            dr["TAHUN"] = "";
            tahun.Rows.Add(dr);

            int min = int.Parse(dt.Rows[0]["TAHUN1"].ToString());
            int max = int.Parse(dt.Rows[0]["TAHUN2"].ToString());
            for (int i = min; i <= max; i++)
            {
                dr = tahun.NewRow();
                dr["TAHUN"] = i;
                tahun.Rows.Add(dr);
            }
        }
        lstTahun.DataSource = tahun;
        lstTahun.DataValueField = "TAHUN";
        lstTahun.DataTextField = "TAHUN";
        lstTahun.DataBind();
    }

    protected void btnCek_Click(object sender, EventArgs e)
    {
        populateList1();
        populateList2();
    }

    private void populateList1()
    {
        //sp_list_barang_keluar_per_lab 2017, 7
        if (string.IsNullOrEmpty(lstTahun.SelectedValue))
        {
            return;
        }

        DataTable dt = new DataTable();
        using (SqlDataAdapter da = new SqlDataAdapter(string.Format("sp_list_barang_keluar_per_lab {0}, {1}", lstTahun.SelectedValue, lstLab.SelectedValue), strConn))
        {
            da.Fill(dt);
        }
        userList.DataSource = dt;
        userList.DataBind();
        btnKirim.Enabled = dt.Rows.Count > 0;

        if (dt.Rows.Count < 1)
        {
            showMessage("Tidak ada data", "Tidak ada daftar permintaan untuk tahun anggaran " + lstTahun.SelectedValue, "success");
        }
    }

    private void populateList2()
    {
        //sp_list_barang_keluar_per_lab 2017, 7
        if (string.IsNullOrEmpty(lstTahun.SelectedValue))
        {
            return;
        }

        DataTable dt = new DataTable();
        using (SqlDataAdapter da = new SqlDataAdapter(string.Format("sp_list_barang_keluar_per_lab_terpenuhi {0}, {1}", lstTahun.SelectedValue, lstLab.SelectedValue), strConn))
        {
            da.Fill(dt);
        }
        list2.DataSource = dt;
        list2.DataBind();
    }
}